package ownthink

import (
	"errors"
	"fmt"
	"gitee.com/ifinder/chat-robot/domain"
	"gitee.com/ifinder/chat-robot/utils"
	"github.com/bitly/go-simplejson"
)
type Ownthink struct {
	// appid=xiaosi&userid=user&spoken=姚明多高啊？
	Appid string
	Userid string


}

func GetOwnthink(appid string,userid string) *Ownthink  {

	//https://api.ownthink.com/bot?spoken=%E5%9C%A8%E5%90%97
	//https://api.ownthink.com/bot?appid=xiaosi&userid=user&spoken=姚明多高啊？

	robot:=Ownthink{
		Appid:appid,
		Userid:userid,
	}
	if robot.Appid==""{
		robot.Appid="xiaosi"
	}
	if robot.Userid==""{
		robot.Userid="user"
	}
	return &robot

}

/*

{
    "message": "success",               // 请求是否成功
    "data": {
        "type": 5000,                   // 答案类型，5000文本类型
        "info": {
            "text": "姚明的身高是226厘米"  // 机器人返回的答案
        }
    }
}
 */
func (this *Ownthink) Say(sayReq *domain.SayReq) (*domain.SayResp,error) {


	var resp domain.SayResp
	apiUrl := fmt.Sprintf("https://api.ownthink.com/bot?appid=%s&userid=%s&spoken=%s",this.Appid,this.Userid,sayReq.Content)
	ret,err:=utils.HTTPGet(apiUrl)

	if err!=nil{
		return nil,err
	}

	myJson, err := simplejson.NewJson(ret)
	if err!=nil{
		return nil,err
	}


	msg,_:=myJson.Get("message").String()
	if msg =="success"{
		i_type,_:=myJson.Get("data").Get("type").Int()
		if i_type==5000 {
			str,err:=myJson.Get("data").Get("info").Get("text").String()
			if err!=nil{
				return nil,err
			}
			resp.Content=str

		}else{
			return nil,errors.New("not support type")
		}
	}else{
		return nil,errors.New(msg)
	}
	return &resp,nil
}
